// member
package models_member

import (
	"martini_template/componnet"
	"martini_template/database"
	"martini_template/models/common"
	"strconv"

	"github.com/satori/go.uuid"
)

type Member struct {
	models_common.BaseModel
	Id             string `xorm:"pk notnull unique"`
	Number         int64  `xorm:"index notnull unique"`
	Username       string `xorm:"notnull unique"`
	Password       string `xorm:"notnull" json:"-"`
	Nickname       string
	Realname       string
	Score          int64 `xorm:"default(0)" json:"-"`
	Balance        float64
	Sex            int
	Birthday       int64
	Avatar         string
	Email          string
	Telphone       string
	RegisterIp     string
	RegisterTime   int64
	AddTime        int64  `xorm:"notnull created" json:"-"`
	LastUpdateTime int64  `xorm:"updated"`
	IsActive       int    `xorm:"default(1)" json:"-"`
	IsDeleted      int    `xorm:"default(0)" json:"-"`
	AccessToken    string `json:"AccessToken" xorm:"-"`
}

type MemberHouseMap struct {
	MemberId   string `xorm:"notnull unique"`
	HouseId    int64  `xorm:"notnull"`
	RelateTime int64  `xorm:"updated"`
	IsDeleted  int    `xorm:"defualt(1)" json:"-"`
}

func (model *Member) SaveMember() (bool, string) {
	if model.Id != "" { //update
		updateFields := "password,nickname,realname,score,balance,sex,birthday,avatar,email,telphone,is_deleted"
		_, err := database.Engine.Id(model.Id).Cols(updateFields).Update(model)
		if err != nil {
			componnet.Elogger.Println(err)
			return false, ""
		} else {
			return true, model.Id
		}
	} else { //insert
		model.Id = uuid.NewV4().String()
		model.Password = componnet.Md5String(model.Password)
		model.IsActive = 1
		lastInsertIdInt, err := database.Engine.Insert(model)
		lastInsertId := strconv.FormatInt(lastInsertIdInt, 10)
		if err == nil {
			return true, lastInsertId
		} else {
			componnet.Elogger.Println(err)
			return false, ""
		}
	}
	return false, ""
}

func (model *Member) Login(username string, password string) (bool, int) {
	loadRes := models_common.LoadByAttr("username", username, model)
	if !loadRes {
		return false, componnet.CODE_MEMBER_ERR_USERNAME
	}
	enPassword := componnet.Md5String(password)
	if enPassword != model.Password {
		return false, componnet.CODE_MEMBER_ERR_PASSWORD
	}
	if model.IsActive == 0 {
		return false, componnet.CODE_MEMBER_ERR_UNACTIVE
	}
	return true, componnet.CODE_SUCC
}

func (model *Member) Banding(houseId int64) bool {
	var mapModel MemberHouseMap
	mapModel.MemberId = model.Id
	mapModel.HouseId = houseId
	_, ierr := database.Engine.InsertOne(mapModel)
	if ierr != nil {
		componnet.Elogger.Println(ierr)
		return false
	} else {
		return true
	}
}
